package com.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import sun.audio.*;

//用于播放背景音乐
public class GameMusic{

	//注：java 支持wav格式 midi格式声音文件
	
	private static AudioStream as; //音频流
	private static InputStream is; //字节流
	private static AudioData ad;   //音频数据源
	private static ContinuousAudioDataStream cads;//音频循环流
	//播放背景音乐 JDK 7 sun.audio.*包实现
	public static void playBgMusic(String path){
		try {
			//实现方式2 需要JDK 1.7支持
			InputStream is=new FileInputStream(path);//获取字节李
			 as=new AudioStream(is);//获取音频流
			//循环播放
			AudioData ad=as.getData();//获取音频数据源
			//音频循环流
			ContinuousAudioDataStream cad=new ContinuousAudioDataStream(ad);
			AudioPlayer.player.start(cad);//循环播放
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//使用默认声音文件 
	public static void playBgMusic(){
		try {
			if(cads==null){
				//获取字节流
				 is= GameMusic.class.getResourceAsStream(GameConstant.MUSIC_PATH);
				 as=new AudioStream(is);//获取音频流
				
				 ad=as.getData();//获取音频数据源
				 cads=new ContinuousAudioDataStream(ad);//获取音频循环流
				AudioPlayer.player.start(cads);//循环播放
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//播放按钮音效
	public static void playClick(){
		try {
			//获取字节流
			InputStream is= GameMusic.class.getResourceAsStream(GameConstant.MUSIC_BTN_PATH);
			AudioStream as=new AudioStream(is);//获取音频流
			AudioPlayer.player.start(as);//播放一次
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	//停止播放背景音乐
	public static void stopBgMusic(){
		AudioPlayer.player.stop(cads);//停止播放
		cads=null;
	}

	
	//JDK 6 javax.sound包实现方式
	public void play(String path)throws Exception{
		File f=new File(path);//加载声音文件
		//获得音频输入流
		AudioInputStream audioInputStream=AudioSystem.getAudioInputStream(f);
		//获取音频编码格式
		AudioFormat audioFormat=audioInputStream.getFormat();
		//音频格式数据行信息
		DataLine.Info dataLine_info=new DataLine.Info(SourceDataLine.class, audioFormat);
		//将音频数据写入数据行的缓冲区
		SourceDataLine sourceDataLine=(SourceDataLine) AudioSystem.getLine(dataLine_info);
		
		byte [] b=new byte[1024];
		int len=0;
		//打开音频数据行
		sourceDataLine.open(audioFormat,1024);
		//创建独立线程进行播放
		sourceDataLine.start();
		//将音频输出
		while((len=audioInputStream.read(b))>0){
			sourceDataLine.write(b, 0, len);
		}
		//关闭音频流
		audioInputStream.close();
		sourceDataLine.drain();
		sourceDataLine.close();
		
	}
	
}
